package com.share51.novel.common.utils;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * 处理文件 解压缩工具
 * @author gb
 */
public class ZipUtil {

    private static final String SUFFIX=".zip";

    /**
     * 注释内容
     */
    public static String COMMENT = "";

    public static String zip(String filePath,boolean del) throws IOException {
        File file=new File(filePath);
        if (!file.exists()){
            throw new IOException("unZip exception because File not found！filePath:"+filePath);
        }
        FileInputStream fis = new FileInputStream(file);
        String fileName=file.getName();
        fileName=fileName.substring(0,fileName.lastIndexOf("."));
        File targetFile=new File(file.getParent()+File.separatorChar+fileName+SUFFIX);
        FileOutputStream fos=new FileOutputStream(targetFile);
        ZipOutputStream zos = new ZipOutputStream(fos);
        try {
            ZipEntry zipEntry=new ZipEntry(file.getName());
            zos.putNextEntry(zipEntry);
            zos.setComment(COMMENT);
            IOUtils.copy(fis,zos);
        } finally {
            zos.closeEntry();
            zos.close();
            fos.close();
            fis.close();
        }
        if (del){
            boolean delete = file.delete();
        }
        return targetFile.getAbsolutePath();
    }

    /**
     * 解压 压缩文件
     * @param zipFilePath
     * @param del
     * @return
     */
    public static String unZip(String zipFilePath,boolean del) throws IOException{
        File file=new File(zipFilePath);
        if (!file.exists()){
            throw new IOException("unZip exception because File not found！filePath:"+zipFilePath);
        }
        FileInputStream fis=new FileInputStream(file);
        ZipInputStream zis = new ZipInputStream(fis);
        InputStream is=null;
        ZipEntry nextEntry = zis.getNextEntry();
        ZipFile zipFile = new ZipFile(file);
        File targetFile = new File(file.getParentFile(),nextEntry.getName());
        try {
            is= zipFile.getInputStream(nextEntry);
            FileUtils.copyInputStreamToFile(is,targetFile);
        } finally {
            fis.close();
            zis.close();
            zipFile.close();
            if (is!=null){
                is.close();
            }
        }
        if (del){
            boolean delete = file.delete();
        }
        return targetFile.getAbsolutePath();
    }
}
